<!-- 用户管理 -->
<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { ref, unref, nextTick, watch, reactive } from 'vue'
import { ElTree, ElInput, ElDivider, ElButton } from 'element-plus'
import { useTable } from '@/hooks/web/useTable'
import { Search } from '@/components/Search'
import { Write, Detail, PwdChange, SetRole } from './components'
import { Dialog } from '@/components/Dialog'
import { Delete } from '@element-plus/icons-vue'
import {
  sysOrgDataList,
  sysUserPageDataList,
  sysUserDataList,
  sysDepartmentDataList,
  sysUserDeleteById,
  sysUserSaveOrUpdate,
  sysUserResetPwd,
  sysGrantBatchGrantRole
} from '@/api/backstage'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'
import { getFirstNode } from '@/utils/tree'
import {
  querySearchAsync,
  handleSelect,
  setContentType,
  delCommonUsage
} from '@/utils/commonUsages'
import { SUCCESS_CODE } from '@/constants'

const { t } = useI18n()

const { tableRegister, tableState, tableMethods } = useTable({
  immediate: false,
  fetchDataApi: async () => {
    const { pageSize, currentPage } = tableState
    const res = await sysUserPageDataList(
      {
        pageNum: unref(currentPage),
        pageSize: unref(pageSize)
      },
      {
        orgId: unref(currentNodeKey),
        ...unref(searchParams)
      }
    )
    return {
      list: res.data.records || [],
      total: res.data.total || 0
    }
  },
  fetchDelApi: async () => {
    const res = await sysUserDeleteById({ id: unref(delId) })
    return !!res
  }
})
const { total, loading, dataList, pageSize, currentPage } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const deptList = ref<any[]>([])
const userList = ref<any[]>([])

const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'index',
    label: t('userDemo.index'),
    form: {
      hidden: true
    },
    search: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      type: 'index'
    }
  },
  {
    field: 'username',
    label: '用户账户'
  },
  {
    field: 'nickname',
    label: '用户昵称'
  },
  {
    field: 'mobile',
    label: '手机号',
    form: {
      componentProps: {
        maxlength: 11,
        minlength: 11,
        showWordLimit: true
      }
    }
  },

  {
    field: 'deptName',
    label: t('userDemo.department'),
    form: {
      hidden: true
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'deptId',
    label: t('userDemo.department'),
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    },
    form: {
      component: 'TreeSelect',
      componentProps: {
        nodeKey: 'id',
        props: {
          label: 'name'
        }
      },
      optionApi: async () => {
        const res = await sysDepartmentDataList({})
        deptList.value = res.data

        return res.data
      }
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'leader',
    label: '直属主管',
    form: {
      hidden: true
    },
    search: {
      hidden: true
    }
  },
  {
    field: 'leaderId',
    label: '直属主管',
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    },
    form: {
      component: 'Select',
      componentProps: {
        props: {
          key: 'id',
          value: 'id',
          label: 'nickname'
        }
      },
      optionApi: async () => {
        const res = await sysUserDataList({ orgId: unref(currentNodeKey) })
        userList.value = res.data
        return res.data
      }
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'jobTitle',
    label: '职务岗位',
    search: {
      hidden: true
    },
    form: {
      component: 'Autocomplete',
      componentProps: {
        placeholder: '快捷存储与选择职务岗位',
        fetchSuggestions: querySearchAsync,
        clearable: false,
        on: {
          select: handleSelect,
          focus: () => {
            setContentType(5)
          }
        },
        slots: {
          default: ({ item }: any) => {
            return (
              <div class="w-full flex justify-between">
                <span>{item.content}</span>
                <ElButton
                  type="danger"
                  link
                  icon={Delete}
                  onClick={($event) => {
                    $event.stopPropagation()
                    $event.preventDefault()
                    delCommonUsage(item.id)
                  }}
                ></ElButton>
              </div>
            )
          },
          suffix: () => {
            return (
              <>
                <BaseButton type="primary" onClick={() => unref(writeRef)?.saveCommon()}>
                  保存
                </BaseButton>
              </>
            )
          }
        }
      }
    }
  },
  {
    field: 'email',
    label: '电子邮箱',
    form: {
      component: 'Input'
    },
    search: {
      hidden: true
    }
  },
  // {
  //   field: 'role',
  //   label: t('userDemo.role'),
  //   search: {
  //     hidden: true
  //   },
  //   form: {
  //     component: 'Select',
  //     value: [],
  //     componentProps: {
  //       multiple: true,
  //       collapseTags: true,
  //       maxCollapseTags: 1
  //     },
  //     optionApi: async () => {
  //       const res = await getRoleListApi()
  //       return res.data?.list?.map((v) => ({
  //         label: v.roleName,
  //         value: v.id
  //       }))
  //     }
  //   }
  // },

  {
    field: 'sortOrder',
    label: '显示排序',
    search: {
      hidden: true
    },
    form: {
      component: 'InputNumber',
      value: 1,
      componentProps: {
        min: 0
      }
    }
  },
  {
    field: 'createTime',
    label: '创建时间',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },
  {
    field: 'createUser',
    label: '创建人',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'updateTime',
    label: '更新时间',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'updateUser',
    label: '修改人',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    table: {
      hidden: true
    }
  },
  {
    field: 'action',
    label: t('userDemo.action'),
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    search: {
      hidden: true
    },
    table: {
      width: 300,
      slots: {
        default: (data: any) => {
          const row = data.row as any
          return (
            <>
              <BaseButton type="primary" link onClick={() => action(row, 'edit')}>
                {t('exampleDemo.edit')}
              </BaseButton>
              <BaseButton type="success" link onClick={() => action(row, 'detail')}>
                {t('exampleDemo.detail')}
              </BaseButton>
              <BaseButton type="danger" link onClick={() => delData(row)}>
                {t('exampleDemo.del')}
              </BaseButton>
              <BaseButton link onClick={() => openMiniDialog(row, 'pwd')}>
                修改密码
              </BaseButton>
              <BaseButton type="primary" link onClick={() => openMiniDialog(row, 'role')}>
                分配角色
              </BaseButton>
            </>
          )
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const searchParams = ref({})
const setSearchParams = (params: any) => {
  console.log('process.env.NODE_ENV', process.env.NODE_ENV)
  currentPage.value = 1
  searchParams.value = params
  getList()
}

const treeEl = ref<typeof ElTree>()

const currentNodeKey = ref('')
const departmentList = ref<any[]>([])
const fetchDepartment = async () => {
  const res = await sysOrgDataList({})
  departmentList.value = res.data || []
  if (res.data.length === 0) return

  const nodeData: any = (res.data.length > 0 && getFirstNode(res.data)) || null
  currentNodeKey.value = nodeData.id || ''
  await nextTick()
  unref(treeEl)?.setCurrentKey(currentNodeKey.value)
  getList()
}
fetchDepartment()

const currentDepartment = ref('')
watch(
  () => currentDepartment.value,
  (val) => {
    unref(treeEl)!.filter(val)
  }
)

const currentChange = (data: any) => {
  // if (data.children) return
  currentNodeKey.value = data.id
  currentPage.value = 1
  getList()
}

const filterNode = (value: string, data: any) => {
  if (!value) return true
  return data.name.includes(value)
}

const miniDialogVisible = ref(false)
const saveMiniLoading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')

const currentRow = ref<any>()
const actionType = ref('')

const AddAction = () => {
  dialogTitle.value = t('exampleDemo.add')
  currentRow.value = {
    orgId: currentNodeKey.value,
    orgName: unref(treeEl)?.getCurrentNode()?.name || ''
  }
  console.log('AddAction', currentRow.value, unref(treeEl)?.getCurrentNode())
  dialogVisible.value = true
  actionType.value = ''
}

const delLoading = ref(false)

const delId = ref('')
const delData = async (row?: any) => {
  delId.value = row.id
  delLoading.value = true

  await delList(1).finally(() => {
    delLoading.value = false
  })
}

const action = (row: any, type: string) => {
  dialogTitle.value = t(type === 'edit' ? 'exampleDemo.edit' : 'exampleDemo.detail')
  actionType.value = type
  currentRow.value = row
  console.log('action', currentRow.value)
  dialogVisible.value = true
}
const openMiniDialog = (row: any, type: string) => {
  dialogTitle.value = type === 'pwd' ? '修改密码' : '分配角色'
  currentRow.value = row
  actionType.value = type
  console.log('openMiniDialog', currentRow.value)
  miniDialogVisible.value = true
}

const writeRef = ref<ComponentRef<typeof Write>>()
const pwdRef = ref<ComponentRef<typeof PwdChange>>()
const roleRef = ref<ComponentRef<typeof SetRole>>()

const saveLoading = ref(false)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  if (formData) {
    saveLoading.value = true
    try {
      if (formData.deptId) {
        formData.deptName = deptList.value.find((item) => item.id === formData.deptId)?.name || ''
      }
      if (formData.leaderId) {
        formData.leader =
          userList.value.find((item) => item.id === formData.leaderId)?.nickname || ''
      }
      console.log('保存提交', formData)

      const res = await sysUserSaveOrUpdate(formData)
      if (res) {
        currentPage.value = 1
        getList()
      }
    } catch (error) {
      console.log(error)
    } finally {
      saveLoading.value = false
      dialogVisible.value = false
    }
  }
}
/** 保存快捷存储 */
// const saveCommon = async () => {
//   const formData = await getFormData()
//   if (!formData.jobTitle) {
//     return
//   }
//   saveCommonUsage(formData.jobTitle)
//   // console.log(formData, formData.roleType)
// }
const savePwd = async () => {
  const pwd = unref(pwdRef)
  const formData = await pwd?.submit()
  if (formData) {
    saveMiniLoading.value = true
    try {
      console.log('修改密码', formData)

      const res = await sysUserResetPwd(formData)
      saveMiniLoading.value = false
      miniDialogVisible.value = false
    } catch (error) {
      console.log(error)
    } finally {
      saveMiniLoading.value = false
      miniDialogVisible.value = false
    }
  }
}

const saveRole = async () => {
  const role = unref(roleRef)
  const formData = await role?.submit()
  if (formData) {
    saveMiniLoading.value = true
    try {
      console.log('分配角色', formData)

      const res = await sysGrantBatchGrantRole(formData)
      if (res.code === SUCCESS_CODE) {
        currentPage.value = 1
        getList()
      }
    } catch (error) {
      console.log(error)
    } finally {
      saveMiniLoading.value = false
      miniDialogVisible.value = false
    }
  }
}

const ElTreeProp = {
  children: 'children',
  label: 'name',
  value: 'id'
}
</script>

<template>
  <div class="flex w-100% h-100%">
    <ContentWrap class="w-250px">
      <div class="flex justify-center items-center">
        <ElInput v-model="currentDepartment" class="flex-[2]" placeholder="机构" clearable />
      </div>
      <ElDivider />
      <ElTree
        ref="treeEl"
        :data="departmentList"
        default-expand-all
        highlight-current
        :expand-on-click-node="false"
        node-key="id"
        :current-node-key="currentNodeKey"
        :props="ElTreeProp"
        :filter-node-method="filterNode"
        @current-change="currentChange"
      />
    </ContentWrap>
    <ContentWrap class="flex-[1]">
      <Search
        :schema="allSchemas.searchSchema"
        @reset="setSearchParams"
        @search="setSearchParams"
        :operationAdd="true"
        :operation-del="false"
        @add="AddAction"
        @batch-del="delData"
      />

      <Table
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :columns="allSchemas.tableColumns"
        :data="dataList"
        :loading="loading"
        @register="tableRegister"
        :pagination="{
          total
        }"
      />
    </ContentWrap>

    <Dialog v-model="dialogVisible" :title="dialogTitle">
      <Write
        v-if="actionType !== 'detail'"
        ref="writeRef"
        :form-schema="allSchemas.formSchema"
        :current-row="currentRow"
      />

      <Detail
        v-if="actionType === 'detail'"
        :detail-schema="allSchemas.detailSchema"
        :current-row="currentRow"
      />

      <template #footer>
        <BaseButton
          v-if="actionType !== 'detail'"
          type="primary"
          :loading="saveLoading"
          @click="save"
        >
          {{ t('exampleDemo.save') }}
        </BaseButton>
        <BaseButton @click="dialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
      </template>
    </Dialog>
    <Dialog v-model="miniDialogVisible" :title="dialogTitle" maxHeight="300" width="500px">
      <PwdChange v-if="actionType === 'pwd'" ref="pwdRef" :current-row="currentRow" />
      <SetRole v-if="actionType === 'role'" ref="roleRef" :current-row="currentRow" />

      <template #footer>
        <BaseButton
          v-if="actionType === 'pwd'"
          type="primary"
          :loading="saveMiniLoading"
          @click="savePwd"
        >
          {{ t('exampleDemo.save') }}
        </BaseButton>
        <BaseButton
          v-if="actionType === 'role'"
          type="primary"
          :loading="saveMiniLoading"
          @click="saveRole"
        >
          {{ t('exampleDemo.save') }}
        </BaseButton>
        <BaseButton @click="miniDialogVisible = false">{{ t('dialogDemo.close') }}</BaseButton>
      </template>
    </Dialog>
  </div>
</template>
